package com.cbg.base.interceptor;

import com.cbg.base.constant.Constant;
import com.cbg.base.utils.UserContextHolder;
import com.cbg.dg.jwt.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * <pre></pre>
 * <small> 2018-12-25 | chenbing </small>
 */
public class AuthTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        String token,userId;
        if(Objects.isNull(token=request.getHeader(Constant.TOKEN)))
            return false;
        UserContextHolder.setUserId(userId= JwtUtils.getUserId(token));
        return JwtUtils.verify(token,userId);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.shutdown();
    }
}
